package com.cskaoyan.javase.reflect._4field;

import com.cskaoyan.javase.reflect.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * Field描述成员变量
 *
 * @since 11:06
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        // 获取Person类的Class
        Class<?> perClazz = Class.forName("com.cskaoyan.javase.reflect.Person");
        Field[] fields = perClazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("--------------------");
        for (Field declaredField : perClazz.getDeclaredFields()) {
            System.out.println(declaredField);
        }
        System.out.println("-------------------");
        System.out.println(perClazz.getDeclaredField("age"));
        System.out.println("-------------------");
        // 演示反射从创建对象开始,到操作成员变量
        Constructor<?> personCon = perClazz.getDeclaredConstructor(String.class);
        // 破解构造器的私有权限
        personCon.setAccessible(true);
        Person p = (Person) personCon.newInstance("长风");
        System.out.println(p);
        // 用反射给age和gender赋值
        Field personAge = perClazz.getDeclaredField("age");
        personAge.setAccessible(true);
        personAge.set(p, 18);
        System.out.println(personAge.get(p));
        System.out.println(p);

        Field personGender = perClazz.getDeclaredField("gender");
        personGender.setAccessible(true);
        personGender.set(p, "女");
        System.out.println(p);
    }
}
